<template>
  <ElSpace :size="size" :spacer="divider ? spacer : ''">
    <template v-for="(action, index) in getActions" :key="`${index}-${action.title}`">
      <ElButton
        v-if="index < size - 1"
        :link="action.link"
        :type="action.type"
        @click="action.onClick"
      >
        <Icon v-if="action.preIcon" :icon="action.preIcon" />
        {{ action.title }}
        <Icon v-if="action.postIcon" :icon="action.postIcon" />
      </ElButton>
    </template>
    <ElDropdown v-if="actions.length > size - 1">
      <ElButton :link="btntype === 'link'" type="primary">
        {{ t('common.more') }}
        <Icon :icon="'ant-design:down-outlined'" />
      </ElButton>
      <template #dropdown>
        <ElDropdown-menu>
          <template v-for="(action, index) in getActions" :key="`${index}-${action.title}`">
            <ElDropdown-item v-if="index > 1">
              <ElButton :link="action.link" :type="action.type" @click="action.onClick">
                <Icon v-if="action.preIcon" :icon="action.preIcon" />
                {{ action.title }}
                <Icon v-if="action.postIcon" :icon="action.postIcon" />
              </ElButton>
            </ElDropdown-item>
          </template>
        </ElDropdown-menu>
      </template>
    </ElDropdown>
  </ElSpace>
</template>
<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n'
import { propTypes } from '@/utils/propTypes'
import { ElSpace, ElButton, ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus'
import { computed, PropType, toRaw } from 'vue'
import { XActionsProps } from './types'

const { t } = useI18n()
const props = defineProps({
  actions: {
    type: Array as PropType<XActionsProps[]>,
    default: null
  }, // 按钮数组
  btntype: propTypes.oneOf(['link', 'default']).def('default'),
  size: propTypes.number.def(4),
  spacer: propTypes.string.def('|'),
  divider: propTypes.bool.def(true), // 是否显示按钮间隔符
  dropdown: propTypes.number.def(3) // 默认超过3个自动变成更多
})

const getActions = computed(() => {
  return (
    (toRaw(props.actions) || [])
      // .filter((action) => {
      //   if (action.auth == 'null') return false
      // })
      .map((action) => {
        if (props.btntype === 'link') {
          return {
            type: action.type || 'primary',
            ...action,
            link: true
          }
        }
        return {
          type: action.type || 'primary',
          ...action
        }
      })
  )
})
</script>
